package com.FengChaoSystem.servlet;

import com.FengChaoSystem.pojo.*;
import com.FengChaoSystem.service.NewImpl;
import com.FengChaoSystem.service.NewService.NewService;
import com.FengChaoSystem.tool.ThreadPool;
import com.FengChaoSystem.tool.TimeTask;
import com.FengChaoSystem.service.CourierImpl;
import com.FengChaoSystem.service.CourierService.CourierService;
import com.FengChaoSystem.service.OrderImpl;
import com.FengChaoSystem.service.OrderService.OrderService;
import com.FengChaoSystem.service.UserImpl;
import com.FengChaoSystem.service.UserService.UserService;
import com.Mybatis.executor.BaseExecutor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@WebServlet("/Courier/*")
public class CourierServlet extends BaseServlet{
    CourierImpl service=new CourierService();
    private org.slf4j.Logger logger = LoggerFactory.getLogger(BaseExecutor.class);

    /**
     * 以下三个就是搜索对应的订单消息
     * @param request
     * @param response
     * @throws Exception
     */

    public void selectAllOrderByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");

        HttpSession session = request.getSession();
        int id= (int)session.getAttribute("userId");
        PageNeed pageNeed=new PageNeed();

        pageNeed.setUserId(id);
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        pageNeed.setSize(Integer.parseInt(pageSize));
        List<Order> orders = service.selectAllOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            String startTime = dateFormat.format(order.getStartTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
            System.out.println(jsonString);
        }
    }

    public void selectAllCanSendOrderByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");

        PageNeed pageNeed=new PageNeed();
        pageNeed.setUserId(id);
        pageNeed.setSize(Integer.parseInt(pageSize));
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        List<Order> orders = service.selectAllCanSendOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            String startTime = dateFormat.format(order.getStartTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
            System.out.println(jsonString);
        }
    }

    public void selectSendingOrderByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String currentPage = request.getParameter("CurrentPage");
        String pageSize = request.getParameter("PageSize");
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");

        PageNeed pageNeed=new PageNeed();
        pageNeed.setUserId(id);
        pageNeed.setSize(Integer.parseInt(pageSize));
        pageNeed.setBegin((Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize));
        List<Order> orders = service.selectSendingOrderByCondition(pageNeed);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order:orders) {
            String startTime = dateFormat.format(order.getStartTime());
            order.setStartTime(null);
            order.setEndTime(null);
            JSONObject orderObject = (JSONObject) JSON.toJSON(order);
            orderObject.put("startTime", startTime);

            // 将整合后的 JSONObject 转换为字符串输出
            String jsonString = orderObject.toJSONString();
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
            System.out.println(jsonString);
        }
    }

    /**
     * 以下三个就是获取对应的数据条数
     * @param request
     * @param response
     * @throws Exception
     */
    public void getCountOfSendingOrders(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");
        User user=new User();
        user.setId(id);
        List<Order> orders = service.selectSendingOrder(user);
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
    public void  getCountOfAllCanSendOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        List<Order> orders = service.selectAllCanSendOrder();
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
    public void  getCountOfAllOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("userId");
        User user=new User();
        user.setId(id);
        List<Order> orders = service.selectAllOrder(user);
        int totalCount = orders.size();
        String jsonString = JSON.toJSONString(totalCount);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    /**
     * 快递员的接单操作
     * @param request
     * @param response
     * @throws Exception
     */
    public void  acceptOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OrderImpl temp=new OrderService();
        String onlyId = request.getParameter("onlyId");
        Order order= new Order();
        order.setOnlyId(onlyId);
        Order result = temp.select(order);

        if(result.getStatus()!=0){
            response.getWriter().write("error");
            return;
        }

        HttpSession session = request.getSession();
        int userId = (int)session.getAttribute("userId");
        order.setTransportId(userId);
        Order temp1 = service.hasBeAccept(order);
        if(temp1!=null){
            response.getWriter().write("error");
            return;
        }

        service.acceptOrder(order);
        order.setStatus(1);
        temp.updateStatus(order);
        response.getWriter().write("success");
    }

    /**
     * 查询所有的货物柜的信息
     * @param request
     * @param response
     * @throws Exception
     */
    public void  selectAllOccupy(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Occupy> occupies1 = service.selectAllOccupy1();
        List<Occupy> occupies2 = service.selectAllOccupy2();
        List<Occupy> occupies3 = service.selectAllOccupy3();

        Occupy[][] result= new Occupy[3][30];
        int number;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 30; j++) {
                result[i][j]=new Occupy();
                result[i][j].setGetNumber(j+1);
                result[i][j].setStatus(1);
            }
        }
        if(occupies1!=null){
        for (Occupy occupy : occupies1) {
            number=occupy.getGetNumber();
            result[0][number-1].setStatus(0);
        }}
        if(occupies2!=null){


        for (Occupy occupy : occupies2) {
            number=occupy.getGetNumber();
            result[1][number-1].setStatus(0);
        } }
        if(occupies3!=null) {
            for (Occupy occupy : occupies3) {
                number = occupy.getGetNumber();
                result[2][number - 1].setStatus(0);
            }
        }
        String jsonString = JSON.toJSONString(result);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

    /**
     * 投放的时候使用，会自动生成取件码，并启动定时任务
     * @param request
     * @param response
     * @throws Exception
     */
    public void  addOccupy(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String onlyId = request.getParameter("onlyId");
        String Address = request.getParameter("getAddress");
        int getAddress=Integer.parseInt(Address);
        String number = request.getParameter("getNumber");
        int getNumber=Integer.parseInt(number);
        Random random=new Random();
        int i = random.nextInt(1000000);
        String getWord=String.valueOf(i);
        Occupy occupy=new Occupy();
        occupy.setGetWord(getWord);
        occupy.setGetAddress(getAddress);
        while(service.hasGetWord(occupy)!=null){
             i = random.nextInt(1000000);
             getWord=String.valueOf(i);
             occupy.setGetWord(getWord);
        }
        occupy.setStatus(0);
        occupy.setGetNumber(getNumber);
        occupy.setOnlyId(onlyId);

        service.addOccupy(occupy);

        OrderImpl temp=new OrderService();
        Order order=new Order();
        order.setOnlyId(onlyId);
        order.setStatus(2);
        temp.updateStatus(order);
        temp.updatePutTime(order);



        OrderImpl orderService=new OrderService();
        Order select = orderService.select(order);
        UserImpl userService=new UserService();
        User user=new User();
        user.setId(select.getToUserId());
        User selectResult = userService.selectUserInfo(user);
        if(selectResult!=null){
            NewImpl newService=new NewService();
            New n=new New();
            n.setUserId(selectResult.getId());
            n.setOnlyId(onlyId);
            newService.addNeedGetNew(n);

            ThreadPool.addTask(selectResult.getEmailAddress(),onlyId,selectResult.getId());
        }
        response.getWriter().write("success");


    }

    }
